package com.tuanzi.loan.business.service.statistics.impl;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.constants.DictionaryCode;
import com.tuanzi.loan.business.entity.common.CommProductId;
import com.tuanzi.loan.business.entity.system.Dictionary;
import com.tuanzi.loan.business.repository.statistics.ActivityParticipateStatRepository;
import com.tuanzi.loan.business.service.common.CommProductIdService;
import com.tuanzi.loan.business.service.statistics.ActivityParticipateStatService;
import com.tuanzi.loan.business.service.system.DictionaryService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.vo.PageSearcher;
import com.tuanzi.loan.vo.request.statistics.ActivityParticipateStatSearchRequest;
import com.tuanzi.loan.vo.response.statistics.ActivityParticipateStatSearchResponse;
import com.tuanzi.server.loan_base.model.bean.common.CommAdvertise;
import com.tuanzi.server.loan_base.model.bean.common.CommPlatform;
import com.tuanzi.server.loan_base.model.bean.common.CommUserType;
import com.tuanzi.server.loan_base.model.db.CommProductChannel;
import com.tuanzi.server.loan_base.model.db.CommProductPrdid;
import com.tuanzi.server.loan_base.model.db.LoanProductInfo;
import org.apache.commons.lang.StringUtils;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 活动参与统计 ServiceImplement
 * @author JinRuiyang 2018/1/26 11:01:09
 */
@Debug
@Service
@Transactional
@Retryable(value = { RetryException.class })
public class ActivityParticipateStatServiceImpl implements ActivityParticipateStatService {

    @Autowired
    private ActivityParticipateStatRepository activityparticipatestatRepository;
    
    @Autowired
	protected DictionaryService dictionaryService;
    
    @Autowired
    private CommProductIdService commProductIdService;
    
    private TreeNode prodNodeTree;

    /**
     * 将所有树形节点设置为未选中状态
     * @param treeNode
     */
    private void cleanSelectedTree(TreeNode treeNode) {
    	treeNode.setSelected(false);
    	List<TreeNode> list1 = treeNode.getChildren();
    	if(list1 != null && list1.size() != 0) {
    		for(TreeNode n1 : list1) {
    			n1.setSelected(false);
    			List<TreeNode> list2 = n1.getChildren();
    			if(list2 != null && list2.size() != 0) {
    				for(TreeNode n2 : list2) {
    					n2.setSelected(false);
    				}
    			}
    		}
    	}
    }
    
    private void defaultSelected(TreeNode prodNodeTree) {
    	List<TreeNode> nodes = prodNodeTree.getChildren();
    	if(nodes != null && nodes.size() != 0) {
    		nodes.get(0).getChildren().get(0).setSelected(true);
    	}
    }
    
    public TreeNode getProductTree() {
    	Map<Integer,List<CommProductPrdid>> prodTreeMap = new HashMap<Integer,List<CommProductPrdid>>();
    	List<CommProductPrdid> productAllList = activityparticipatestatRepository.getProduct();
    	if(productAllList != null && productAllList.size() != 0) {
    		for(CommProductPrdid prod : productAllList) {
    			Integer parentId = Integer.valueOf(prod.getParent_id());
    			List<CommProductPrdid> prodList = prodTreeMap.get(parentId);
    			if(prodList == null) {
    				prodList = Lists.newArrayList();
    			}
    			prodList.add(prod);
    			prodTreeMap.put(parentId, prodList);
    		}
    	}
    	
    	prodNodeTree = new DefaultTreeNode("Root", null);
    	prodNodeTree.setExpanded(true);
    	
    	CommProductPrdid allProdP = new CommProductPrdid();
    	allProdP.setPrdid(-1000);
    	allProdP.setName("全部");
    	allProdP.setLevel(1);
    	TreeNode allProdNodeP = new DefaultTreeNode(allProdP, prodNodeTree);
    	allProdNodeP.setSelected(true);
    	CommProductPrdid allProdS = new CommProductPrdid();
    	allProdS.setPrdid(-1000);
    	allProdS.setName("展示全部");
    	allProdS.setLevel(2);
    	new DefaultTreeNode(allProdS, allProdNodeP).setSelected(true);
    	
    	for (Map.Entry<Integer, List<CommProductPrdid>> entry : prodTreeMap.entrySet()) {
    		Integer largeProductId = entry.getKey();
    		if(-1000 == largeProductId.intValue()) {
    			continue;
    		}
    		Dictionary dictionary = dictionaryService.findByCodeAndValue1(DictionaryCode.LARGE_COMMON_PRODUCT, String.valueOf(largeProductId));
    		
    		CommProductPrdid largeProd = new CommProductPrdid();
    		largeProd.setPrdid(largeProductId);
    		largeProd.setLevel(1);
    		if(dictionary == null) {
    			largeProd.setName("未知");
    		} else {
    			largeProd.setName(dictionary.getName());
    		}
    		
    		TreeNode largeProdNode = new DefaultTreeNode(largeProd, prodNodeTree);
    		List<CommProductPrdid> prodList = entry.getValue();
    		for(CommProductPrdid prod : prodList) {
    			prod.setLevel(2);
    			prod.setName(prod.getName());
    			new DefaultTreeNode(prod, largeProdNode);
    		}
    	}
    	
    	return prodNodeTree;
    }

    /**
     * ActivityParticipateStat查询
     * @param pageSearcher 请求信息
     * @return 响应列表
     */
    public Page<ActivityParticipateStatSearchResponse> list(PageSearcher<ActivityParticipateStatSearchRequest> pageSearcher) {
		ActivityParticipateStatSearchRequest searchCondition = pageSearcher.getSearchCondition();
		TreeNode[] selectedChannelNodes = searchCondition.getSelectedChannelNodes();
		List<Integer> channels = new ArrayList<>();
		List<Integer> channelGroupList = new ArrayList<>();
		if(null != selectedChannelNodes && selectedChannelNodes.length > 0){
			for (TreeNode treeNode : selectedChannelNodes) {
				com.tuanzi.loan.business.entity.common.CommProductChannel  data = (com.tuanzi.loan.business.entity.common.CommProductChannel) treeNode.getData();
				Integer channelCode = data.getChannelCode();
				if(channelCode != null){
					channels.add(channelCode);
				}
				Integer channelGroup = data.getChannelGroup();
				if(null != channelGroup && channelCode != null && -1000 == channelCode){
					channelGroupList.add(channelGroup);
				}
			}
		}
		searchCondition.setChannelId(channels);
		searchCondition.setChannelGroupList(channelGroupList);

		TreeNode[] selectedProductNodes = searchCondition.getSelectedProductNodes();
		List<Integer> products = new ArrayList<>();
		List<String> parentIdList = new ArrayList<>();
		if(null != selectedProductNodes && selectedProductNodes.length > 0){
			for (TreeNode treeNode : selectedProductNodes) {
				CommProductId data = (CommProductId) treeNode.getData();
				Integer productId = data.getProductId();
				if(null != productId){
					products.add(productId);
				}
				String parentId = data.getParentId();
				if(StringUtils.isNotBlank(parentId) && null != productId && -1000 == productId){
					parentIdList.add(parentId);
				}
			}
		}
		searchCondition.setProductId(products);
		searchCondition.setParentIdList(parentIdList);

		return activityparticipatestatRepository.list(searchCondition,pageSearcher.getPageable());
    }

    @Override
    public void cleanCache() {
    	prodNodeTree = null;
        activityparticipatestatRepository.cleanCache();
    }

    @Override
    public List<CommProductPrdid> getProduct() {
        return activityparticipatestatRepository.getProduct();
    }

    @Override
    public List<CommProductChannel> getChannel() {
        return activityparticipatestatRepository.getChannel();
    }

    @Override
    public List<CommPlatform> getPlatform() {
        return activityparticipatestatRepository.getPlatform();
    }

    @Override
    public List<CommUserType> getUserType() {
        return activityparticipatestatRepository.getUserType();
    }

    @Override
    public List<CommAdvertise> getAD() {
        return activityparticipatestatRepository.getAD();
    }

    @Override
    public List<LoanProductInfo> getActivity() {
        return activityparticipatestatRepository.getActivity();
    }
}